package com.uziot.bucket.utils;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.oracle.visitor.OracleSchemaStatVisitor;
import com.alibaba.druid.stat.TableStat;
import com.alibaba.druid.util.JdbcConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author shidt
 * @version V1.0
 * @className TableUtils
 * @date 2022-06-04 22:18:33
 * @description
 */

@Slf4j
public class TableUtils {
    private static List<String> getTableNameBySql(String sql) {
        String dbType = JdbcConstants.ORACLE;
        try {
            List<String> tableNameList = new ArrayList<>();
            //格式化输出
            String sqlResult = SQLUtils.format(sql, dbType);
            log.info("格式化后的sql:[{}]", sqlResult);
            List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
            if (CollectionUtils.isEmpty(stmtList)) {
                log.info("stmtList为空⽆需获取");
                return Collections.emptyList();
            }
            for (SQLStatement sqlStatement : stmtList) {
                OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
                sqlStatement.accept(visitor);
                Map<TableStat.Name, TableStat> tables = visitor.getTables();
                log.info("druid解析sql的结果集:[{}]", tables);
                Set<TableStat.Name> tableNameSet = tables.keySet();
                for (TableStat.Name name : tableNameSet) {
                    String tableName = name.getName();
                    if (!StringUtils.isEmpty(tableName)) {
                        tableNameList.add(tableName);
                    }
                }
            }
            log.info("解析sql后的表名:[{}]", tableNameList);
            return tableNameList;
        } catch (Exception e) {
            log.error("**************异常SQL:[{}]*****************\\n", sql);
            log.error(e.getMessage(), e);
        }
        return Collections.emptyList();
    }
}
